package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.barlibrary.ImmersionBar
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.*
import com.kanshu.ksgb.fastread.doudou.common.view.CustomDialog
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent
import com.kanshu.ksgb.fastread.doudou.common.business.event.TaskEvent
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindPhoneInfo
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_bind_phone.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

@Route(path = ARouterConfig.PERSONAL_BIND_PHONE)
class BindPhoneActivity : BaseActivity() {
    var viewType = BIND_PHONE
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bind_phone)
        viewType = intent.getIntExtra("type", BIND_PHONE)
        initView()
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            loadingDialog!!.dismiss()
        }
        EventBus.getDefault().unregister(this)
    }


    override fun initStatusbar() {
        try {
            mImmersionBar = ImmersionBar.with(this);
            mImmersionBar.keyboardEnable(true);
            mImmersionBar.init()
            if (ImmersionBar.isSupportStatusBarDarkFont())
                mImmersionBar.statusBarDarkFont(true).init();
        } catch (e: Exception) {
        }
        val statusBarHeight = DisplayUtils.getStatusBarHeight(this);
        val params = mTitle.getLayoutParams() as LinearLayout.LayoutParams;
        params.topMargin = statusBarHeight
        mTitle.setLayoutParams(params);
    }

    private fun initView() {
        if (viewType == BIND_PHONE) {
            invited_code_container.visibility = View.VISIBLE
            invited_code_divider.visibility = View.VISIBLE
            val menu = TextView(this)
            menu.setText("已有账号")
            menu.setTextColor(resources.getColor(R.color.dlg_sure_color))
            menu.setOnClickListener {
                finish()
                var map = HashMap<String,Integer>()
                map["type"] = Integer(BindPhoneActivity.LOGIN_PHONE)
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_BIND_PHONE, map)
            }
            //remove switch phone function
            // mTitle.rightContainer.addView(menu)
        }
        mTitle.setTitle("绑定手机号")
        btn_commit.setOnClickListener {
            val phoneNum = phone_input.text.toString()
            if (TextUtils.isEmpty(phoneNum) || phoneNum.length != 11) {
                ToastUtil.showMessage("输入的手机号码格式不正确")
                return@setOnClickListener
            }

            val validateCode = validate_code.text.toString()
            if (TextUtils.isEmpty(validateCode) || validateCode.length != 4) {
                ToastUtil.showMessage("输入的验证码不正确")
                return@setOnClickListener
            }
            val inviteCode = invited_code.text.toString()
            doSubmit(phoneNum, validateCode, inviteCode)
        }
        btn_get_code.setOnClickListener { getValidateCode() }
    }

    private fun getValidateCode() {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            return
        }
        loadingDialog = LoadingDialog(this, "")
        val phoneNum = phone_input.text.toString()
        if (TextUtils.isEmpty(phoneNum) || phoneNum.length != 11) {
            ToastUtil.showMessage("输入的手机号码格式不正确")
            return
        }
        val helper = RetrofitHelper.getInstance()
        val params = mutableMapOf<String, String>()
        params.put("phone", phoneNum)
        val personService = helper.createService(PersonCenterService::class.java)
        btn_get_code.setTextColor(resources.getColor(R.color.btn_disable))
        btn_get_code.isEnabled = false
        personService.getValidateCode(params)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<String>> {
                    override fun onComplete() {
                        loadingDialog?.dismiss()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        loadingDialog?.show()
                    }

                    override fun onNext(t: BaseResult<String>?) {
                        val code = t?.result?.status?.code ?: -1
                        if (code == 0) {
                            ToastUtil.showMessage("获取验证码成功")
                            startCountDown()
                        } else {
                            ToastUtil.showMessage("获取验证码失败,请稍后再试")
                        }
                    }

                    override fun onError(e: Throwable?) {
                        ToastUtil.showMessage("获取验证码失败,请稍后再试")
                        e?.printStackTrace()
                        loadingDialog?.dismiss()
                    }
                })
    }

    private fun startCountDown() {
        Observable.intervalRange(1, VALIDATION_EXPIRE_TIME + 1, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(lifeCyclerSubject)
                .subscribe {
                    updateContDownView(VALIDATION_EXPIRE_TIME - it)
                }

    }

    @SuppressLint("SetTextI18n")
    private fun updateContDownView(timeLeft: Long) {
        if (timeLeft <= 0) {
            btn_get_code.isEnabled = true
            btn_get_code.text = "获取验证码"
            btn_get_code.setTextColor(resources.getColor(R.color.btn_enable))
            return
        }
        btn_get_code.text = "${timeLeft}s"
    }


    private fun doSubmit(phoneNum: String, validateCode: String, inviteCode: String?) {
        val params = mutableMapOf<String, String?>()
        params.put("phone", phoneNum)
        params.put("code", validateCode)
        if (!TextUtils.isEmpty(inviteCode)) {
            params.put("invitation_code", inviteCode)
        }
        val helper = RetrofitHelper.getInstance()
        val personService = helper.createService(PersonCenterService::class.java)
        when (viewType) {
            BIND_PHONE -> doBindPhone(personService, params)
            LOGIN_PHONE -> doLoginPhone(personService, params)
        }

    }

    var loadingDialog: LoadingDialog? = null

    private fun doBindPhone(personService: PersonCenterService, params: MutableMap<String, String?>) {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            return
        }
        loadingDialog = LoadingDialog(this, "")

        personService.bindPhoneNum(params)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<BindPhoneInfo>> {
                    override fun onComplete() {
                        loadingDialog?.dismiss()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        loadingDialog?.show()
                    }

                    override fun onNext(t: BaseResult<BindPhoneInfo>?) {
                        val code = t?.result?.status?.code ?: -1
                        if (code == 0) {
                            doBindSuccess(t?.result?.data)
                        } else {
                            ToastUtil.showMessage("绑定失败:${t?.result?.status?.msg}")
                            if (code == 81007) { //手机已绑定
                                doBindFail()
                            }
                        }


                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        loadingDialog?.dismiss()
                    }
                })

    }

    private fun doBindFail() {
/*        val dialog = CustomDialog.show()
        val layout = LayoutInflater.from(this).inflate(R.layout.layout_phone_used,null) as ViewGroup
        dialog.setContentView(layout)*/
        val dialog = CustomDialog(this);
        dialog.goneTitle()
        dialog.setCancelBtnText("更换手机号")
        dialog.setSureBtnText("取消")
        dialog.setContent("手机号已注册")
        dialog.setCallback(object : CustomDialog.Callback {
            override fun onSure(dialog: Dialog?) {
                dialog?.dismiss()
                //actionStart(this@BindPhoneActivity, LOGIN_PHONE)
            }

            override fun onCancel(dialog: Dialog?) {
                dialog?.dismiss()
                phone_input.setText("")
                validate_code.setText("")
                invited_code.setText("")
            }

        })

        dialog.show()

    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 99)
    fun handleBindEvent(event: BindEvent) {
        if (event.code == BindEvent.SUCCESS) {
            finish()
        }
    }

    private fun doBindSuccess(bindPhoneInfo: BindPhoneInfo?) {
        if (bindPhoneInfo != null) {
            StorageUtils.setPreference<String>(activity, Constants.SP_NAME, Constants.USER_BIND_PHONE + bindPhoneInfo.user_id, bindPhoneInfo.phone)
            UserUtils.saveUserId(bindPhoneInfo.user_id)
            EventBus.getDefault().post(TaskEvent(TaskEvent.BIND_PHONE))
            val bindEvent = BindEvent()
            bindEvent.code = BindEvent.SUCCESS
            bindEvent.data = bindPhoneInfo.phone
            EventBus.getDefault().post(bindEvent)

            var map = HashMap<String, Parcelable>()
            map["data"] = bindPhoneInfo
            ARouterUtils.toActivity(ARouterConfig.PERSONAL_BIND_RESULT, map)
            finish()
        }
    }

    private fun doLoginPhone(personService: PersonCenterService, params: MutableMap<String, String?>) {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            return
        }
        loadingDialog = LoadingDialog(this, "")

        personService.bindPhoneNum(params)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<BindPhoneInfo>> {
                    override fun onComplete() {
                        loadingDialog?.dismiss()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        loadingDialog?.show()
                    }

                    override fun onNext(t: BaseResult<BindPhoneInfo>?) {
                        val code = t?.result?.status?.code ?: -1
                        if (code == 0) {
                            UserUtils.saveUserId(t?.result?.data?.user_id)
                            val bindEvent = BindEvent()
                            bindEvent.code = BindEvent.SUCCESS
                            EventBus.getDefault().post(bindEvent)
                            finish()
                        } else {
                            ToastUtil.showMessage("登录失败:${t?.result?.status?.msg}")
                        }
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        loadingDialog?.dismiss()
                    }
                })
    }


    companion object {
        const val VALIDATION_EXPIRE_TIME = 60L
        const val BIND_PHONE = 1
        const val LOGIN_PHONE = 2
        fun actionStart(activity: Activity, type: Int) {
            val intent = Intent(activity, BindPhoneActivity::class.java)
            intent.putExtra("type", type)
            activity.startActivity(intent)
        }
    }
}
